import paho.mqtt.client as mqtt
import json
import base64
import cv2
import numpy as np
from flask import Flask, render_template, Response, request
import multiprocessing
import flask_video.ObjectDection as od

app = Flask(__name__)

## 最底层进程 订阅客户端进程
def GetPicfromEMQ(q):

    def on_connect(client, userdata, flags, rc):
        print("Connected with result code: " + str(rc))

    def on_message(client, userdata, msg):
        if msg.topic == 'R&C':
            radarTarget = json.loads(msg.payload)
            # print(jdata)
            picinfo = bytes(radarTarget['picinfo'],'utf-8')
            img = base64.b64decode(picinfo)
            # b_img = img.tobytes()
            # # 图片展示 转化为cv2格式
            nparr = np.frombuffer(img, np.uint8)
            img = cv2.imdecode(nparr,cv2.IMREAD_COLOR)
            # img = od.ObjectDect(img)
            # img = od.TagOnPic(radarTarget,img)
            q.put(img)

    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.username_pw_set("sub", "123")
    client.connect('192.168.56.101', 1883, 600)  # 600为keepalive的时间间隔
    client.subscribe('R&C', qos=0)

    client.loop_forever()  # 保持连接

## 顶层进程 web显示
def DisplayOnWeb(q):

    def get_frame():
        img = q.get()
        return img

    @app.route('/')  # 主页
    def index():
        # jinja2模板，具体格式保存在index.html文件中
        return render_template('index.html')


    def gen():
        while True:
            frame = get_frame()
            ret, jpeg = cv2.imencode('.jpg', frame)
            # 使用generator函数输出视频流， 每次请求输出的content类型是image/jpeg
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + jpeg.tobytes() + b'\r\n\r\n')

    @app.route('/video_feed')  # 这个地址返回视频流响应
    def video_feed():
        return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')

    app.run(host='192.168.43.8', port=8099)

def run():
    # 传递数据的队列 共享单元 默认一次传递一个大小 因此大小位1
    q = multiprocessing.Queue()

    p1 = multiprocessing.Process(target=GetPicfromEMQ, args=(q,))
    p2 = multiprocessing.Process(target=DisplayOnWeb, args=(q,))
    p1.start()
    p2.start()

if __name__ == '__main__':
    run()




